﻿namespace Dcms.Common
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;

    public class Utils
    {
        public static string check_TxtSql(string sqlStr)
        {
            string SQL_injdata = "'|or|and|exec|insert|select|delete|update|create|*|truncate|char|drop|depth";
            string Unicode_Str = "";
            string[] sql_Arr = SQL_injdata.ToString().Split(new char[] { '|' });
            for (int j = 0; j < sql_Arr.Length; j++)
            {
                Unicode_Str = ToUnicode(sql_Arr[j].ToString());
                sqlStr = sqlStr.ToLower().Replace(sql_Arr[j].ToString(), Unicode_Str);
            }
            return sqlStr;
        }

        public static string ChkSQL(string str)
        {
            if (str == null) return "";
            str = str.Replace("'", "''");
            return str;
        }

        public static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        }

        public static string ClearBR(string str)
        {
            Regex r = null;
            Match m = null;
            r = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
            for (m = r.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), "");
            }
            return str;
        }

        public static string ClearHtml(string strHtml)
        {
            if (strHtml != "")
            {
                Regex r = null;
                Match m = null;
                r = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
                for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
                {
                    strHtml = strHtml.Replace(m.Groups[0].ToString(), "");
                }
            }
            return strHtml;
        }

        public static bool CreateDir(string name)
        {
            return MakeSureDirectoryPathExists(name);
        }

        public static string cutString(string strInput, int intLen)
        {
            strInput = strInput.Trim();
            if (Encoding.Default.GetBytes(strInput).Length <= intLen) return strInput;
            string resultStr = "";
            for (int i = 0; i < strInput.Length; i++)
            {
                if (Encoding.Default.GetBytes(resultStr).Length < intLen - 4)
                    resultStr = resultStr + strInput.Substring(i, 1);
                else
                    break;
            }
            return (resultStr + " ...");
        }

        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        public static string CutString(string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length *= -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                        startIndex -= length;
                }
                if (startIndex > str.Length) return "";
            }
            else if (length >= 0 && length + startIndex > 0)
            {
                length += startIndex;
                startIndex = 0;
            }
            else
                return "";
            if (str.Length - startIndex < length) length = str.Length - startIndex;
            try
            {
                return str.Substring(startIndex, length);
            }
            catch
            {
                return str;
            }
        }

        public static string DESDeCode(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 0x10);
                inputByteArray[x] = (byte) i;
            }
            des.Key = Encoding.ASCII.GetBytes(sKey);
            des.IV = Encoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return HttpContext.Current.Server.UrlDecode(Encoding.Default.GetString(ms.ToArray()));
        }

        public static string DESEnCode(string pToEncrypt, string sKey)
        {
            pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
            des.Key = Encoding.ASCII.GetBytes(sKey);
            des.IV = Encoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        public static string EncodeHtml(string strHtml)
        {
            if (strHtml != "")
            {
                strHtml = strHtml.Replace(",", "&def");
                strHtml = strHtml.Replace("'", "&dot");
                strHtml = strHtml.Replace(";", "&dec");
                return strHtml;
            }
            return "";
        }

        public static bool FileExists(string filename)
        {
            return File.Exists(filename);
        }

        public static string[] FindNoUTF8File(string Path)
        {
            StringBuilder filelist = new StringBuilder();
            FileInfo[] subFiles = new DirectoryInfo(Path).GetFiles();
            for (int j = 0; j < subFiles.Length; j++)
            {
                if (subFiles[j].Extension.ToLower().Equals(".htm"))
                {
                    FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
                    bool bUtf8 = IsUTF8(fs);
                    fs.Close();
                    if (!bUtf8)
                    {
                        filelist.Append(subFiles[j].FullName);
                        filelist.Append("\r\n");
                    }
                }
            }
            return SplitString(filelist.ToString(), "\r\n");
        }

        public static string FormatBytesStr(int bytes)
        {
            double csTemp0002;
            if (bytes > 0x40000000)
            {
                csTemp0002 = bytes / 0x40000000;
                return (csTemp0002.ToString("0") + "G");
            }
            if (bytes > 0x100000)
            {
                csTemp0002 = bytes / 0x100000;
                return (csTemp0002.ToString("0") + "M");
            }
            if (bytes > 0x400)
            {
                csTemp0002 = bytes / 0x400;
                return (csTemp0002.ToString("0") + "K");
            }
            return (bytes.ToString() + "Bytes");
        }

        public static string FormatDataTime(string DateTimeStr, string StyleStr)
        {
            if (DateTimeStr == null || DateTimeStr == "") return "-----";
            if (DateTimeStr.Substring(0, 4) != "0001" && DateTimeStr.Substring(0, 4) != "1888")
            {
                try
                {
                    return Convert.ToDateTime(DateTimeStr).ToString(StyleStr);
                }
                catch (Exception)
                {
                    return DateTimeStr;
                }
            }
            return "--------";
        }

        public static string FormatStrProcess(string parentlist, int Step)
        {
            int tempParentlist = 1;
            if (parentlist == "") return "001";
            if (parentlist.Length >= 3) parentlist = parentlist.Substring(parentlist.Length - 3, 3);
            tempParentlist = Convert.ToInt16(parentlist) + Step;
            if (tempParentlist.ToString().Length < 3)
            {
                int i = 1;
                int j = 1;
                j = tempParentlist.ToString().Length;
                parentlist = tempParentlist.ToString();
                for (i = j; i < 3; i++)
                {
                    parentlist = "0" + parentlist;
                }
            }
            return parentlist;
        }

        public static string GetAssemblyCopyright()
        {
            return FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).LegalCopyright;
        }

        public static string GetAssemblyProductName()
        {
            return FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName;
        }

        public static string GetAssemblyVersion()
        {
            FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
            return string.Format("{0}.{1}.{2}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart);
        }

        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null) return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            return "0";
        }

        public static string GetDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd");
        }

        public static string GetDate(string datetimestr, string replacestr)
        {
            if (datetimestr == null) return replacestr;
            if (datetimestr.Equals("")) return replacestr;
            try
            {
                datetimestr = Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr);
            }
            catch
            {
                return replacestr;
            }
            return datetimestr;
        }

        public static string GetDateTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string GetDateTime(int relativeday)
        {
            return DateTime.Now.AddDays((double) relativeday).ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string GetDateTimeF()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
        }

        public static int GetDiffDate(DateTime BeginDate, DateTime Enddate, int DateType)
        {
            try
            {
                TimeSpan temp = (TimeSpan) (Enddate - BeginDate);
                switch (DateType.ToString())
                {
                    case "1":
                        return temp.Days;

                    case "2":
                        return temp.Hours;

                    case "3":
                        return temp.Minutes;

                    case "4":
                        return temp.Seconds;

                    case "5":
                        return temp.Milliseconds;
                }
                return temp.Days;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static string GetEmailHostName(string strEmail)
        {
            if (strEmail.IndexOf("@") < 0) return "";
            return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
        }

        public static string GetFilename(string url)
        {
            if (url == null) return "";
            string[] strs1 = url.Split(new char[] { '/' });
            return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
        }

        public static string GetHtmlEditReplace(string str)
        {
            return str.Replace("'", "''").Replace("&nbsp;", " ").Replace(",", "，").Replace("%", "％").Replace("script", "").Replace(".js", "");
        }

        public static int GetInArrayID(string strSearch, string[] stringArray)
        {
            return GetInArrayID(strSearch, stringArray, true);
        }

        public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
        {
            for (int i = 0; i < stringArray.Length; i++)
            {
                if (caseInsensetive)
                {
                    if (strSearch.ToLower() == stringArray[i].ToLower()) return i;
                }
                else if (strSearch == stringArray[i]) return i;
            }
            return -1;
        }

        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null) return HttpContext.Current.Server.MapPath(strPath);
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
        }

        public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;
            if (url.IndexOf("?") > 0)
                url = url + "&";
            else
                url = url + "?";
            string t1 = "<a href=\"" + url + "&page=1\">&laquo;</a>&nbsp;";
            string t2 = string.Concat(new object[] { "<a href=\"", url, "&page=", countPage, "\">&raquo;</a>&nbsp;" });
            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;
            if (countPage > extendPage)
            {
                if (curPage - extendPage / 2 > 0)
                {
                    if (curPage + extendPage / 2 < countPage)
                    {
                        startPage = curPage - extendPage / 2;
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }
            StringBuilder s = new StringBuilder("");
            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                if (i == curPage)
                {
                    s.Append("&nbsp;");
                    s.Append(i);
                    s.Append("&nbsp;");
                }
                else
                {
                    s.Append("&nbsp;<a href=\"");
                    s.Append(url);
                    s.Append("page=");
                    s.Append(i);
                    s.Append("\">");
                    s.Append(i);
                    s.Append("</a>&nbsp;");
                }
            }
            s.Append(t2);
            return s.ToString();
        }

        public static string GetPostPageNumbers(int countPage, string url, string expname, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;
            int curPage = 1;
            string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
            string t2 = string.Concat(new object[] { "<a href=\"", url, "-", countPage, expname, "\">&raquo;</a>&nbsp;" });
            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;
            if (countPage > extendPage)
            {
                if (curPage - extendPage / 2 > 0)
                {
                    if (curPage + extendPage / 2 < countPage)
                    {
                        startPage = curPage - extendPage / 2;
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }
            StringBuilder s = new StringBuilder("");
            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                s.Append("&nbsp;<a href=\"");
                s.Append(url);
                s.Append("-");
                s.Append(i);
                s.Append(expname);
                s.Append("\">");
                s.Append(i);
                s.Append("</a>&nbsp;");
            }
            s.Append(t2);
            return s.ToString();
        }

        public static string GetRealIP()
        {
            return DcmsRequest.GetIP();
        }

        public static string GetStandardDateTime(string fDateTime)
        {
            return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
        }

        public static string GetStandardDateTime(string fDateTime, string formatStr)
        {
            return Convert.ToDateTime(fDateTime).ToString(formatStr);
        }

        public static string GetStaticPageNumbers(int curPage, int countPage, string url, string expname, int extendPage)
        {
            int startPage = 1;
            int endPage = 1;
            string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
            string t2 = string.Concat(new object[] { "<a href=\"", url, "-", countPage, expname, "\">&raquo;</a>&nbsp;" });
            if (countPage < 1) countPage = 1;
            if (extendPage < 3) extendPage = 2;
            if (countPage > extendPage)
            {
                if (curPage - extendPage / 2 > 0)
                {
                    if (curPage + extendPage / 2 < countPage)
                    {
                        startPage = curPage - extendPage / 2;
                        endPage = startPage + extendPage - 1;
                    }
                    else
                    {
                        endPage = countPage;
                        startPage = endPage - extendPage + 1;
                        t2 = "";
                    }
                }
                else
                {
                    endPage = extendPage;
                    t1 = "";
                }
            }
            else
            {
                startPage = 1;
                endPage = countPage;
                t1 = "";
                t2 = "";
            }
            StringBuilder s = new StringBuilder("");
            s.Append(t1);
            for (int i = startPage; i <= endPage; i++)
            {
                if (i == curPage)
                {
                    s.Append("&nbsp;");
                    s.Append(i);
                    s.Append("&nbsp;");
                }
                else
                {
                    s.Append("&nbsp;<a href=\"");
                    s.Append(url);
                    s.Append("-");
                    s.Append(i);
                    s.Append(expname);
                    s.Append("\">");
                    s.Append(i);
                    s.Append("</a>&nbsp;");
                }
            }
            s.Append(t2);
            return s.ToString();
        }

        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
        {
            string myResult = p_SrcString;
            if (p_Length < 0) return myResult;
            byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
            if (bsSrcString.Length <= p_Length) return myResult;
            int nRealLength = p_Length;
            int[] anResultFlag = new int[p_Length];
            byte[] bsResult = null;
            int nFlag = 0;
            for (int i = 0; i < p_Length; i++)
            {
                if (bsSrcString[i] > 0x7f)
                {
                    nFlag++;
                    if (nFlag == 3) nFlag = 1;
                }
                else
                    nFlag = 0;
                anResultFlag[i] = nFlag;
            }
            if (bsSrcString[p_Length - 1] > 0x7f && anResultFlag[p_Length - 1] == 1) nRealLength = p_Length + 1;
            bsResult = new byte[nRealLength];
            Array.Copy(bsSrcString, bsResult, nRealLength);
            return (Encoding.Default.GetString(bsResult) + p_TailString);
        }

        public static string GetTime()
        {
            return DateTime.Now.ToString("HH:mm:ss");
        }

        public static string GetTrueForumPath()
        {
            string forumPath = HttpContext.Current.Request.Path;
            if (forumPath.LastIndexOf("/") != forumPath.IndexOf("/")) return forumPath.Substring(forumPath.IndexOf("/"), forumPath.LastIndexOf("/") + 1);
            return "/";
        }

        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        public static bool InArray(string str, string[] stringarray)
        {
            return InArray(str, stringarray, false);
        }

        public static bool InArray(string str, string stringarray)
        {
            return InArray(str, SplitString(stringarray, ","), false);
        }

        public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
        {
            return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
        }

        public static bool InArray(string str, string stringarray, string strsplit)
        {
            return InArray(str, SplitString(stringarray, strsplit), false);
        }

        public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
        {
            return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
        }

        public static bool InIPArray(string ip, string[] iparray)
        {
            string[] userip = SplitString(ip, ".");
            for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
            {
                string[] tmpip = SplitString(iparray[ipIndex], ".");
                int r = 0;
                for (int i = 0; i < tmpip.Length; i++)
                {
                    if (tmpip[i] == "*") return true;
                    if (userip.Length > i && tmpip[i] == userip[i])
                        r++;
                    else
                        break;
                }
                if (r == 4) return true;
            }
            return false;
        }

        public static string IntToStr(int intValue)
        {
            return Convert.ToString(intValue);
        }

        public static bool IsBase64String(string str)
        {
            return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
        }

        public static bool IsCompriseStr(string str, string stringarray, string strsplit)
        {
            if (stringarray != "" && stringarray != null)
            {
                str = str.ToLower();
                string[] stringArray = SplitString(stringarray.ToLower(), strsplit);
                for (int i = 0; i < stringArray.Length; i++)
                {
                    if (str.IndexOf(stringArray[i]) > -1) return true;
                }
            }
            return false;
        }

        public static bool IsDateString(string str)
        {
            return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
        }

        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1) return false;
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif";
        }

        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static bool IsNumber(string strNumber)
        {
            return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
        }

        public static bool IsNumberArray(string[] strNumber)
        {
            if (strNumber == null) return false;
            if (strNumber.Length < 1) return false;
            foreach (string id in strNumber)
            {
                if (!IsNumber(id)) return false;
            }
            return true;
        }

        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        public static bool IsSafeUserInfoString(string str)
        {
            return !Regex.IsMatch(str, "/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\"\\s\\t\\<\\>\\&]|$guestexp/is");
        }

        public static bool IsTime(string timeval)
        {
            return Regex.IsMatch(timeval, "^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
        }

        private static bool IsUTF8(FileStream sbInputStream)
        {
            bool bAllAscii = true;
            long iLen = sbInputStream.Length;
            byte cOctets = 0;
            for (int i = 0; i < iLen; i++)
            {
                byte chr = (byte) sbInputStream.ReadByte();
                if ((chr & 0x80) != 0) bAllAscii = false;
                if (cOctets == 0)
                {
                    if (chr >= 0x80)
                    {
                        do
                        {
                            chr = (byte) (chr << 1);
                            cOctets = (byte) (cOctets + 1);
                        }
                        while ((chr & 0x80) != 0);
                        cOctets = (byte) (cOctets - 1);
                        if (cOctets == 0) return false;
                    }
                }
                else
                {
                    if ((chr & 0xc0) != 0x80) return false;
                    cOctets = (byte) (cOctets - 1);
                }
            }
            if (cOctets > 0) return false;
            if (bAllAscii) return false;
            return true;
        }

        public static bool IsValidEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        [DllImport("dbgHelp", SetLastError=true)]
        private static extern bool MakeSureDirectoryPathExists(string name);
        public static string mashSQL(string str)
        {
            if (str == null) return "";
            str = str.Replace("'", "'");
            return str;
        }

        public static string MD5(string str)
        {
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
            {
                ret = ret + b[i].ToString("x").PadLeft(2, '0');
            }
            return ret;
        }

        public static string RemoveHtml(string content)
        {
            string regexstr = "<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }

        public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
        {
            return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
        }

        public static string ReplaceStrToScript(string str)
        {
            str = str.Replace(@"\", @"\\");
            str = str.Replace("'", @"\'");
            str = str.Replace("\"", "\\\"");
            return str;
        }

        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;
            byte[] buffer = new byte[0x2710];
            try
            {
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
                long dataToRead = iStream.Length;
                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));
                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        int length = iStream.Read(buffer, 0, 0x2710);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new byte[0x2710];
                        dataToRead -= length;
                    }
                    else
                        dataToRead = -1;
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null) iStream.Close();
            }
            HttpContext.Current.Response.End();
        }

        public static string RTrim(string str)
        {
            for (int i = str.Length; i >= 0; i--)
            {
                char csTemp0001 = str[i];
                if (!csTemp0001.Equals(" ")) csTemp0001 = str[i];
                if (csTemp0001.Equals("\r") || (csTemp0001 = str[i]).Equals("\n")) str.Remove(i, 1);
            }
            return str;
        }

        public static int SafeInt32(object objNum)
        {
            if (objNum != null)
            {
                string strNum = objNum.ToString();
                if (IsNumber(strNum))
                {
                    if (strNum.ToString().Length > 9) return 0x7fffffff;
                    return int.Parse(strNum);
                }
            }
            return 0;
        }

        public static string setPage(string htmlPage)
        {
            string PageStr;
            int i;
            string ReplaceStr = "<div style=\"page-break-after: always\"><span style=\"display: none\">&nbsp;</span></div>";
            string[] PageInfo = Regex.Split(htmlPage, ReplaceStr, RegexOptions.IgnoreCase);
            int pageNow = DcmsRequest.GetQueryInt("cpage", 1);
            int pageTotal = PageInfo.Length;
            if (pageNow > pageTotal)
                PageStr = PageInfo[pageTotal - 1].ToString();
            else if (pageNow < 1)
                PageStr = PageInfo[0].ToString();
            else
                PageStr = PageInfo[pageNow - 1].ToString();
            string LinkUrl = DcmsRequest.GetRawUrl();
            if (LinkUrl.IndexOf('?') != -1) LinkUrl = LinkUrl.Split(new char[] { '?' })[0];
            LinkUrl = LinkUrl + "?";
            if (HttpContext.Current.Request.QueryString.Count > 0)
            {
                for (i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
                {
                    if (i == 0)
                    {
                        if (HttpContext.Current.Request.QueryString.GetKey(i).ToString().ToLower() != "cpage") LinkUrl = LinkUrl + HttpContext.Current.Request.QueryString.GetKey(i) + "=" + HttpContext.Current.Request.QueryString.GetValues(i)[0];
                    }
                    else if (HttpContext.Current.Request.QueryString.GetKey(i).ToString().ToLower() != "cpage") LinkUrl = LinkUrl + "&" + HttpContext.Current.Request.QueryString.GetKey(i) + "=" + HttpContext.Current.Request.QueryString.GetValues(i)[0];
                }
                if (LinkUrl.Split(new char[] { '?' })[1].Length > 0) LinkUrl = LinkUrl + "&";
            }
            string html = "";
            if (PageInfo.Length > 1)
            {
                string[] csTemp0003;
                string csTemp0004;
                int csTemp0005;
                html = "<div style=\"text-align:center;\" class=\"c_page\">";
                if (pageNow > 1)
                {
                    csTemp0004 = html + "<a class=\"c_first\" href=" + LinkUrl + "cpage=1><img src=\"/Skin/SysImages/xxx_01.jpg\" border=\"0\" /></a>&nbsp;";
                    csTemp0003 = new string[6];
                    csTemp0003[0] = csTemp0004;
                    csTemp0003[1] = "<a class=\"c_pre\" href=";
                    csTemp0003[2] = LinkUrl;
                    csTemp0003[3] = "cpage=";
                    csTemp0005 = pageNow - 1;
                    csTemp0003[4] = csTemp0005.ToString();
                    csTemp0003[5] = "><img src=\"/Skin/SysImages/xxx_02.jpg\" border=\"0\" /></a>&nbsp;";
                    html = string.Concat(csTemp0003);
                }
                else
                    html = html + "<a class=\"c_first\"><img src=\"/Skin/SysImages/xxx_01.jpg\" border=\"0\" /></a>&nbsp;" + "<a class=\"c_pre\"><img src=\"/Skin/SysImages/xxx_02.jpg\" border=\"0\" /></a>&nbsp;";
                for (i = 1; i <= PageInfo.Length; i++)
                {
                    if (i == pageNow)
                        html = html + "<a class=\"c_curpage\">" + i.ToString() + "</a>&nbsp;";
                    else
                    {
                        csTemp0004 = html;
                        html = csTemp0004 + "<a class=\"c_num\" href=" + LinkUrl + "cpage=" + i.ToString() + ">" + i.ToString() + "</a>&nbsp;";
                    }
                }
                if (pageNow + 1 > PageInfo.Length)
                    html = html + "<a class=\"c_next\"><img src=\"/Skin/SysImages/xxx_04.jpg\" border=\"0\" /></a>&nbsp;<a class=\"c_end\"><img src=\"/Skin/SysImages/xxx_03.jpg\" border=\"0\" /></a></div>";
                else
                {
                    csTemp0004 = html;
                    csTemp0003 = new string[10];
                    csTemp0003[0] = csTemp0004;
                    csTemp0003[1] = "<a class=\"c_next\" href=";
                    csTemp0003[2] = LinkUrl;
                    csTemp0003[3] = "cpage=";
                    csTemp0005 = pageNow + 1;
                    csTemp0003[4] = csTemp0005.ToString();
                    csTemp0003[5] = "><img src=\"/Skin/SysImages/xxx_04.jpg\" border=\"0\" /></a>&nbsp;<a class=\"c_end\" href=";
                    csTemp0003[6] = LinkUrl;
                    csTemp0003[7] = "cpage=";
                    csTemp0003[8] = PageInfo.Length.ToString();
                    csTemp0003[9] = "><img src=\"/Skin/SysImages/xxx_03.jpg\" border=\"0\" /></a></div>";
                    html = string.Concat(csTemp0003);
                }
            }
            return (PageStr + html);
        }

        public static string SHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            return Convert.ToBase64String(Sha256.ComputeHash(SHA256Data));
        }

        public static string Spaces(int nSpaces)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < nSpaces; i++)
            {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }

        public static string[] SplitString(string strContent, string strSplit)
        {
            if (strContent.IndexOf(strSplit) < 0) return new string[] { strContent };
            return Regex.Split(strContent, strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
        }

        public static int StrDateDiffHours(string time, int hours)
        {
            if (time == "" || time == null) return 1;
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(time).AddHours((double) hours));
            if (ts.TotalHours > 2147483647.0) return 0x7fffffff;
            if (ts.TotalHours < -2147483648.0) return -2147483648;
            return (int) ts.TotalHours;
        }

        public static int StrDateDiffMinutes(string time, int minutes)
        {
            if (time == "" || time == null) return 1;
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(time).AddMinutes((double) minutes));
            if (ts.TotalMinutes > 2147483647.0) return 0x7fffffff;
            if (ts.TotalMinutes < -2147483648.0) return -2147483648;
            return (int) ts.TotalMinutes;
        }

        public static int StrDateDiffSeconds(string Time, int Sec)
        {
            TimeSpan ts = (TimeSpan) (DateTime.Now - DateTime.Parse(Time).AddSeconds((double) Sec));
            if (ts.TotalSeconds > 2147483647.0) return 0x7fffffff;
            if (ts.TotalSeconds < -2147483648.0) return -2147483648;
            return (int) ts.TotalSeconds;
        }

        public static string StrFilter(string str, string bantext)
        {
            string text1 = "";
            string text2 = "";
            string[] textArray1 = SplitString(bantext, "\r\n");
            for (int num1 = 0; num1 < textArray1.Length; num1++)
            {
                text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
                text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
                str = str.Replace(text1, text2);
            }
            return str;
        }

        public static string StrFormat(string str)
        {
            if (str == null) return "";
            str = str.Replace("\r\n", "<br />");
            str = str.Replace("\n", "<br />");
            return str;
        }

        public static float StrToFloat(object strValue, float defValue)
        {
            if (strValue == null || strValue.ToString().Length > 10) return defValue;
            float intValue = defValue;
            if (strValue != null && new Regex(@"^([-]|[0-9])[0-9]*(\.\w*)?$").IsMatch(strValue.ToString())) intValue = Convert.ToSingle(strValue);
            return intValue;
        }

        public static int StrToInt(object strValue, int defValue)
        {
            if (strValue == null || strValue.ToString() == string.Empty || strValue.ToString().Length > 10) return defValue;
            string val = strValue.ToString();
            string firstletter = val[0].ToString();
            if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1) return defValue;
            if (!(val.Length != 10 || IsNumber(firstletter))) return defValue;
            int intValue = defValue;
            if (strValue != null && new Regex("^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString())) intValue = Convert.ToInt32(strValue);
            return intValue;
        }

        public static string ToUnicode(string str)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(str);
            for (int j = 0; j < bytes.Length; j += 2)
            {
                if (bytes[j + 1] == 0)
                {
                    bytes[j] = (byte) (bytes[j] - 0x20);
                    bytes[j + 1] = 0xff;
                }
            }
            return new string(Encoding.Unicode.GetChars(bytes));
        }

        public void transHtml(string path, string outpath)
        {
            FileStream fs;
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            if (File.Exists(page.Server.MapPath("") + @"\" + outpath))
            {
                File.Delete(page.Server.MapPath("") + @"\" + outpath);
                fs = File.Create(page.Server.MapPath("") + @"\" + outpath);
            }
            else
                fs = File.Create(page.Server.MapPath("") + @"\" + outpath);
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }

        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null) cookie = new HttpCookie(strName);
            cookie.Value = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null) cookie = new HttpCookie(strName);
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes((double) expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static string[] Monthes
        {
            get
            {
                return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            }
        }
    }
}

